package com.sct.wnd.tb;

import java.util.Date;

import android.os.Environment;

import com.friendlyarm.AndroidSDK.HardwareControler;
import com.sct.utils.ADLog;
import com.sct.utils.DateTimeUtils;
import com.sct.utils.FileOperate;
import com.sct.utils.TransformUtil;

public class ReadDataRunnable implements Runnable {
	private int fd;
	public static String THREADLOGPATH = Environment.getExternalStorageDirectory() + "/" + "SCAppTest_Thread.log";
	FileOperate fileOperate;
	private boolean isRun = true;
	private int rTimes = 100;
	public void setRun(boolean isRun) {
		this.isRun = isRun;
	}

	public ReadDataRunnable() {
		try {
			if(null == fileOperate) {
				fileOperate = new FileOperate(THREADLOGPATH);
				fileOperate.prepare();
			}
			fd = HardwareControler.openSerialPort("/dev/s3c2410_serial3", 115200, 8, 1);
			if (fd != -1) {
				fileOperate.writelineToEnd(DateTimeUtils.getDateTime(new Date()) + " => open success");
				fileOperate.writelineToEnd(DateTimeUtils.getDateTime(new Date()) + " fd => " + fd);
				ADLog.info("open success");
			} else {
				fileOperate.writelineToEnd(DateTimeUtils.getDateTime(new Date()) + " => open failed");
				ADLog.info("open failed");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			int count = 0;
			while(isRun) {
				getData();
				count++;
				ADLog.info("count => " +count);
				try
				{
					Thread.sleep(10);
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}

			if (fd != 0 && fd != -1) {
				HardwareControler.close(fd);
			}
			fileOperate.finish();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public void getData() throws Exception {
		
		//fileOperate.writelineToEnd(DateTimeUtils.getDateTime(new Date()) + " fd => " + fd);
		ADLog.info("write empty line!");
		byte[] datas=new byte[32];
		int length = 0;
		if(HardwareControler.select(fd, 1, 0)==1) {
			length=HardwareControler.read(fd, datas, 32);
			if(length > 0)
				fileOperate.writelineToEnd(DateTimeUtils.getDateTime(new Date()) +" " + length + " => " + TransformUtil.bytesToHexString(datas) );
			ADLog.info("write data line!");
		}
	}
	
}
